package com.pureut.system.util;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author: CM
 * @date: 2023/6/26  14:33
 */
public class DownTemplateUtil {

    public static void downTemplate(HttpServletResponse response,String filePath) throws IOException {
        File file = new File(filePath);

        String fileName = filePath.substring(filePath.lastIndexOf("/")+1, filePath.length());

        ByteArrayOutputStream baos = null;
        ServletOutputStream out = null;
        try {

            InputStream inStream=new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            baos = new ByteArrayOutputStream();
            while ((len = inStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            out = response.getOutputStream();
            out.write(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.flush();
            baos.close();
            out.flush();
            out.close();
        }
    }

}
